package com.digital.herbarium.Util;

import java.awt.AlphaComposite;
import java.awt.Font;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class Watermark {

    public static void addWaterMark(String inputFile,  String text)  {
        File file = new File(inputFile);
        BufferedImage image = null;
        String outputFile = inputFile;
        try {
            image = ImageIO.read(file);
            int imgWidth = 3456;
            int imgHeight = 5016;
            if(image != null){
                imgWidth = image.getWidth();
                imgHeight = image.getHeight();
                // 创建水印子类
                Graphics2D g2d = (Graphics2D) image.getGraphics();
                g2d.setColor(Color.DARK_GRAY);
                g2d.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 50));
                // 设置透明度，取值范围为0~1
                g2d.setComposite(java.awt.AlphaComposite.getInstance(java.awt.AlphaComposite.SRC_ATOP, 0.5f));

                // 在图片顶部平铺添加文字，计算每行文字的起始坐标
                int lineHeight = g2d.getFontMetrics().getHeight() * 2;
                int y = lineHeight;
                int textWidth = g2d.getFontMetrics().stringWidth(text);
                int startX = (imgWidth - textWidth) / 2;
//        int startX = 10;
                AffineTransform at = AffineTransform.getRotateInstance(Math.toRadians(45), imgWidth / 2.0, imgHeight / 2.0);
                g2d.setTransform(at);
                while (y < imgWidth) {
                    for (int i = 0; i < text.length(); i++) {
                        char c = text.charAt(i);
                        int charWidth = g2d.getFontMetrics().charWidth(c);
                        g2d.drawString(String.valueOf(c), startX, y);
                        startX += charWidth;
                    }

                    startX += textWidth;
                    y += lineHeight;
                    startX = startX % imgWidth;
                }
                // 保存输出图片
                g2d.dispose();
                File output = new File(outputFile);
                ImageIO.write(image, "jpg", output);
            }


        } catch (IOException e) {
            e.printStackTrace();
            System.out.println(e.toString());
        }


    }
}
